
public class Solution {

  static class TreeNode {
      int val;
      TreeNode left;
      TreeNode right;
      TreeNode() {}
      TreeNode(int val) { this.val = val; }
      TreeNode(int val, TreeNode left, TreeNode right) {
          this.val = val;
          this.left = left;
          this.right = right;
      }
  }

    public String tree2str(TreeNode root) {
        StringBuilder stringBuilder = new StringBuilder();
        tree2strchild(root, stringBuilder);
        return stringBuilder.toString();
    }
    public void tree2strchild(TreeNode root, StringBuilder stringBuilder){
        if(root == null){
            return;
        }
        stringBuilder.append(root.val);
        if(root.left != null){
            stringBuilder.append("(");
            tree2strchild(root.left, stringBuilder);
            stringBuilder.append(")");
        }else{
            if(root.right != null){
                stringBuilder.append("()");
            }else{
                return;
            }
        }
        if(root.right != null){
            stringBuilder.append("(");
            tree2strchild(root.right, stringBuilder);
            stringBuilder.append(")");
        }else{
            return;
        }
    }
}